package org.to_zero.ssm.sdm.interceptor;


import org.springframework.web.servlet.HandlerInterceptor;
import org.to_zero.ssm.sdm.entity.User;
import org.to_zero.ssm.sdm.util.RedisUtil;
import org.to_zero.ssm.sdm.util.Toolkit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.logging.Logger;

public class LoginInterceptor implements HandlerInterceptor {

    private Logger logger = Logger.getLogger("info");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String path = uri.substring(uri.lastIndexOf("/") + 1);
        String token = Toolkit.getToken(request);
        RedisUtil<User> redisUtil = new RedisUtil<>(User.class);
        User user = redisUtil.get(token);
        if (Objects.nonNull(user)) {
            logger.info(path + " 登录放行");
            return true;
        } else {
            response.getWriter().write("403");
        }
        return false;
    }
}
